package com.witmore.neutron.ai.mcp.server.trading.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockAbnormalRecordRequest;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockAbnormalRecordResponse;
import com.witmore.neutron.ai.mcp.server.trading.service.StockAbnormalRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 股票异动记录API控制器
 * 提供股票异动记录的查询接口
 */
@Slf4j
@RestController
@RequestMapping("/api/stock-abnormal-record")
@Tag(name = "股票异动记录API", description = "股票异动记录的查询和详情接口")
public class StockAbnormalRecordApiController {

    @Autowired
    private StockAbnormalRecordService stockAbnormalRecordService;

    /**
     * 分页查询股票异动记录
     */
    @PostMapping("/query")
    @Operation(summary = "分页查询股票异动记录", description = "根据条件分页查询用户的股票异动记录")
    public ResponsePageResult<StockAbnormalRecordResponse> queryAbnormalRecords(@RequestBody StockAbnormalRecordRequest request) {
        try {
            log.info("接收到分页查询异动记录请求: userId={}, page={}, size={}",
                request.getUserId(), request.getPage(), request.getSize());

            // 参数校验
            String validationError = validateQueryRequest(request);
            if (validationError != null) {
                log.warn("分页查询异动记录请求参数校验失败: {}", validationError);
                return ResponsePageResult.fail(400, validationError);
            }

            // 调用服务层分页查询
            Page<StockAbnormalRecordResponse> pageResult =
                stockAbnormalRecordService.queryAbnormalRecords(
                    request.getUserId(),
                    request.getStockCode(),
                    request.getStockName(),
                    request.getAbnormalTypeCode(),
                    request.getStartDate(),
                    request.getEndDate(),
                    request.getPage(),
                    request.getSize()
                );

            log.info("分页查询股票异动记录成功: userId={}, total={}", request.getUserId(), pageResult.getTotal());
            return ResponsePageResult.success(pageResult);

        } catch (Exception e) {
            log.error("分页查询股票异动记录失败: userId={}", request.getUserId(), e);
            return ResponsePageResult.fail(500, "分页查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取股票异动记录详情
     */
    @GetMapping("/get/{recordId}")
    @Operation(summary = "获取异动记录详情", description = "根据ID获取指定的股票异动记录详情")
    public ResponseResult<StockAbnormalRecordResponse> getAbnormalRecord(
            @PathVariable Long recordId) {
        try {
            log.info("接收到获取异动记录详情请求: recordId={}", recordId);

            // 参数校验
            if (recordId == null || recordId <= 0) {
                return ResponseResult.fail(400, "记录ID不能为空且必须大于0");
            }

            // 调用服务层获取详情
            StockAbnormalRecordResponse record = stockAbnormalRecordService.getAbnormalRecordById(recordId);

            if (record != null) {
                log.info("获取异动记录详情成功: recordId={}", recordId);
                return ResponseResult.success(record);
            } else {
                log.warn("异动记录不存在或无权限访问: recordId={}", recordId);
                return ResponseResult.fail(404, "记录不存在或无权限访问");
            }

        } catch (Exception e) {
            log.error("获取异动记录详情失败: recordId={}", recordId, e);
            return ResponseResult.fail(500, "获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取股票异动预警详情
     */
    @GetMapping("/alert-detail/{alertId}")
    @Operation(summary = "获取异动预警详情", description = "根据预警ID获取异动预警详情")
    public ResponseResult<Object> getAlertDetail(
            @PathVariable Integer alertId) {
        try {
            log.info("接收到获取异动预警详情请求: alertId={}", alertId);

            // 参数校验
            if (alertId == null || alertId <= 0) {
                return ResponseResult.fail(400, "预警ID不能为空且必须大于0");
            }

            // 调用服务层获取预警详情
            Object alertDetail = stockAbnormalRecordService.getAlertDetail(alertId);

            if (alertDetail != null) {
                log.info("获取异动预警详情成功: alertId={}", alertId);
                return ResponseResult.success(alertDetail);
            } else {
                log.warn("异动预警不存在或无权限访问: alertId={}", alertId);
                return ResponseResult.fail(404, "预警不存在或无权限访问");
            }

        } catch (Exception e) {
            log.error("获取异动预警详情失败: alertId={}", alertId, e);
            return ResponseResult.fail(500, "获取失败: " + e.getMessage());
        }
    }

    /**
     * 校验查询请求参数
     */
    private String validateQueryRequest(StockAbnormalRecordRequest request) {
        if (request == null) {
            return "请求参数不能为空";
        }
        if (request.getUserId() == null || request.getUserId() <= 0) {
            return "用户ID不能为空且必须大于0";
        }
        if (request.getPage() <= 0) {
            return "页码必须大于0";
        }
        if (request.getSize() <= 0 || request.getSize() > 100) {
            return "页大小必须大于0且不能超过100";
        }
        return null;
    }
}
